package com.zhengqiangblog.blog.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.zhengqiangblog.blog.admin.form.ArticleForm;
import com.zhengqiangblog.blog.exception.ResourceNotFoundException;
import com.zhengqiangblog.blog.model.Article;
import com.zhengqiangblog.blog.model.Category;
import com.zhengqiangblog.blog.model.Pagination;
import com.zhengqiangblog.blog.service.ArticleService;
import com.zhengqiangblog.blog.service.CategoryService;
import com.zhengqiangblog.blog.service.PaginationCalculator;
import com.zhengqiangblog.blog.web.form.PageForm;
import com.zhengqiangblog.core.ApplicationContext;
import com.zhengqiangblog.core.Model;

public class AdminArticleAction {

	private static final Logger logger = Logger.getLogger(AdminArticleAction.class);

	private ArticleService articleService = ApplicationContext.get(ArticleService.class);
	private PaginationCalculator paginationCalculator = ApplicationContext.get(PaginationCalculator.class);
	private CategoryService categoryService = ApplicationContext.get(CategoryService.class);

	public AdminArticleAction() {
		logger.info("AdminArticleAction initializing...");
	}

	public String execute(Model model, PageForm form) throws Exception {
		int totalItems = articleService.getArticleIdList().size();
		Pagination pagination = paginationCalculator.calculate(form.getPage(), totalItems);
		model.addAttribute("pagination", pagination);
		int start = (pagination.getPageNo() - 1) * pagination.getPageSize();
		List<Article> articles = articleService.getArticleList(start, pagination.getPageSize());
		model.addAttribute("articles", articles);
		return "ADMIN_ARTICLE_LIST";
	}

	public String addInit(Model model) throws Exception {
		this.initCategoryList(model);
		return "ADMIN_ARTICLE_ADD";
	}

	public String editInit(Model model) throws Exception {
		String strId = model.getPathVariable("id");
		if (StringUtils.isNoneBlank(strId)) {
			int id = Integer.parseInt(strId);
			Article article = articleService.getArticle(id);
			if (article != null) {
				ArticleForm articleForm = new ArticleForm();
				articleForm.setId(article.getId());
				articleForm.setCategoryId(article.getCategoryId());
				articleForm.setTitle(article.getTitle());
				articleForm.setOverview(article.getOverview());
				articleForm.setContent(article.getContent());
				articleForm.setAuthor(article.getAuthor());
				model.addAttribute("form", articleForm);
			} else {
				throw new ResourceNotFoundException();
			}
		}
		this.initCategoryList(model);
		return "ADMIN_ARTICLE_EDIT";
	}

	public String add(Model model, ArticleForm articleForm) throws Exception {
		List<String> messages = this.validateForm(articleForm);
		if (messages.size() > 0) {
			model.addAttribute("messages", messages);
			model.addAttribute("form", articleForm);
			this.initCategoryList(model);
			return "ADMIN_ARTICLE_ADD";
		}
		Article article = new Article();
		article.setCategoryId(articleForm.getCategoryId());
		article.setTitle(articleForm.getTitle());
		article.setOverview(articleForm.getOverview());
		article.setContent(articleForm.getContent());
		article.setAuthor(articleForm.getAuthor());
		Date date = new Date();
		article.setPostDate(date);
		article.setEditDate(date);
		article.setViews(0);
		article.setStatus(0);
		try {
			articleService.saveArticle(article);
		} catch (Exception e) {
			logger.error("Saving article error", e);
			messages.add("保存文章失败，异常原因：" + e.getMessage());
			model.addAttribute("messages", messages);
			model.addAttribute("form", articleForm);
			this.initCategoryList(model);
			return "ADMIN_ARTICLE_ADD";
		}
		model.addResultParam("namespace", "/admin");
		model.addResultParam("action", "/article");
		return "ADMIN_ARTICLE_LIST";
	}

	public String edit(Model model, ArticleForm articleForm) throws Exception {
		List<String> messages = this.validateForm(articleForm);
		if (messages.size() > 0) {
			model.addAttribute("messages", messages);
			model.addAttribute("form", articleForm);
			this.initCategoryList(model);
			return "ADMIN_ARTICLE_ADD";
		}
		Article article = new Article();
		article.setId(articleForm.getId());
		article.setCategoryId(articleForm.getCategoryId());
		article.setTitle(articleForm.getTitle());
		article.setOverview(articleForm.getOverview());
		article.setContent(articleForm.getContent());
		article.setAuthor(articleForm.getAuthor());
		article.setEditDate(new Date());
		try {
			articleService.updateArticle(article);
		} catch (Exception e) {
			logger.error("Saving article error", e);
			messages.add("保存文章失败，异常原因：" + e.getMessage());
			model.addAttribute("messages", messages);
			model.addAttribute("form", articleForm);
			this.initCategoryList(model);
			return "ADMIN_ARTICLE_ADD";
		}
		model.addResultParam("namespace", "/admin");
		model.addResultParam("action", "/article");
		return "ADMIN_ARTICLE_LIST";
	}

	private List<String> validateForm(ArticleForm articleForm) throws Exception {
		List<String> messages = new ArrayList<String>();
		if (articleForm.getCategoryId() <= 0) {
			messages.add("请选择分类");
			Category category = categoryService.getCategory(articleForm.getCategoryId());
			if (category == null) {
				messages.add("该分类不存在，请重新选择分类");
			}
		}
		if (StringUtils.isBlank(articleForm.getTitle())) {
			messages.add("标题不能为空");
		}
		if (StringUtils.isBlank(articleForm.getOverview())) {
			messages.add("概述不能为空");
		}
		if (StringUtils.isBlank(articleForm.getContent())) {
			messages.add("正文不能为空");
		}
		if (StringUtils.isBlank(articleForm.getAuthor())) {
			messages.add("作者不能为空");
		}
		return messages;
	}

	private void initCategoryList(Model model) throws Exception {
		List<Category> categoryList = categoryService.getCategoryList();
		model.addAttribute("categoryList", categoryList);
	}

}
